// pages/spellWord/spellWord.js
const app = getApp();
let tool = require('../../utils/tool.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    percent: 0,
    totalNum: 0,
    imageUrl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    gameSecond: 50,
    gameSecond2: 50,
    timer: '',
    worldList: {},
    curWord: {},
    spellWord: '',
    curIndex: 0,
    innerAudioContext: new Object(),
    maskDis: 'flex',
    jbDis: 'flex',
    curSplit: -1,
    choiceArr: [],
    spellWrongTime: 0,
    errword: [],
    allword: [],
    rightWord: [],
    res_img: 'fuxi_xhjc_dui_press@2x.png',
    res_color: "",
    res_dis: "false",
    ishide: '1',  //页面是否隐藏，如黑屏
    date: '', //学习日期
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.totalInit();
    let spellPro = this.getData();
    let that = this;
    //获取传过来的日期
    that.setData({
      date: app.globalData.studyDate,
    })
    console.log(that.data.date)
    this.data.innerAudioContext = wx.createInnerAudioContext()
    this.data.innerAudioContext.autoplay = false;
    this.data.innerAudioContext.loop = false;

    spellPro.then(function(res) {
      if (res.code == 1) {
        // res.data.word[0] = res.data.word[0].slice(0, 2)
        for (let ele of res.data.word[0]) {
          that.data.allword.push(ele.id);
        }
        that.setData({
          worldList: res.data.word[0],
          totalNum: res.data.word[0].length
        })
      } else if (res.data.code == 10001) {
        wx.redirectTo({
          url: '/pages/login/login',
        })
      } else {
        wx.showToast({
          title: res.info,
          icon: 'none',
          duration: 2000
        })
        let timerName = setTimeout(function() {
          wx.switchTab({
            url: '../review/review',
          })
        }, 1500)
        return;
      }
    });
    that.data.curIndex = 0;
    clearInterval(that.data.timer);
  },
  setSec: function(e) { //设置描述
    this.setData({
      maskDis: 'none',
      jbDis: 'none',
      gameSecond2: (e.currentTarget.dataset.passsce >= 10) ? e.currentTarget.dataset.passsce : ("0" + e.currentTarget.dataset.passsce),
      gameSecond: (e.currentTarget.dataset.passsce >= 10) ? e.currentTarget.dataset.passsce : ("0" + e.currentTarget.dataset.passsce)
    });
    this.daojishi('pass');
  },
  nextPass: function() {
    clearInterval(this.data.timer);
    if (this.data.curIndex < this.data.worldList.length) {
      this.setData({
        gameSecond: this.data.gameSecond2
      });
      this.setData({ //初始化
        curWord: this.data.worldList[this.data.curIndex],
        spellWord: '',
        choiceArr: [],
        curSplit: -10,
        spellWrongTime: 0,
        curIndex: this.data.curIndex,
        gameSecond: this.data.gameSecond2,
      });
      this.data.curIndex = this.data.curIndex + 1;
      this.playmp3(this.data.curWord.vedio_url);
    } else { //答题完毕
      clearInterval(this.data.timer);
    }
  },
  choice: function(e) {
    let that = this;
    if (this.data.choiceArr.indexOf(e.currentTarget.dataset.idx) == -1) {
      let tmp = this.data.choiceArr;
      tmp.push(e.currentTarget.dataset.idx);
      let spworld = this.data.spellWord + e.currentTarget.dataset.subw
      this.setData({
        choiceArr: tmp,
        spellWord: spworld
      })
      if (this.data.spellWord == this.data.curWord.word) { //拼对了
        this.playmp3(app.globalData.mp3.doright)
        clearInterval(this.data.timer);
        this.setData({
          res_img: 'fuxi_xhjc_dui_press@2x.png',
          res_dis: 'false',
          res_color: '#27BFA3'
        })

        // this.data.rightWord.push(this.data.curWord.id);
        //第一次做错就算错，判断拼错的下次数，如果错误次数为0，这个单词才是真的第一次就是拼对的
        if (this.data.spellWrongTime === 0) {
          this.data.rightWord.push(this.data.curWord.id);
        }

        setTimeout(function() {
          that.daojishi('pass')
        }, 1000);
      }

      if (this.data.choiceArr.length == this.data.curWord.split.length) {
        this.setData({
          res_img: 'fuxi_xhjc_cuo_press@2x.png',
          res_dis: 'false',
          res_color: '#FF6767'
        })
        //判断错误的次数，一次词拼错三次的话自动跳转下一个
        this.playmp3(app.globalData.mp3.selectwrong);
        if (this.data.spellWrongTime < 2) {
          this.data.spellWrongTime = this.data.spellWrongTime + 1;

          app.vibrateShortTap();
          setTimeout(function() {
            that.cancel()
          }, 1000);

        } else {
          //错误效果 抖动   音效
          clearInterval(this.data.timer);
          app.vibrateShortTap();
          setTimeout(function() {
            that.daojishi('pass');
          }, 1000);

        }

      }

    }
    this.setData({
      curSplit: e.currentTarget.dataset.idx
    })
  },
  cancel: function() {
   
    this.setData({
      spellWord: '',
      curSplit: -1,
      choiceArr: [],
      res_dis: 'none',
      res_color: '#333333'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log("spellword界面onShow")
    let that =this;
    if (that.data.ishide == 2) {
      that.setData({
        ishide: 1
      })
      that.daojishi("");
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    // this.totalInit();
    console.log("spellword界面onHide")
    this.setData({
      ishide: 2
    })
    clearInterval(this.data.timer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log("spellword界面onUnload")
    this.totalInit();
    clearInterval(this.data.timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**
   * 获取数据
   */
  getData: function() {
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    let paramArr = {
      access_token: app.globalData.studentInfo.access_token,
      date: app.globalData.studyDate
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "review/compose?sign=" + sign;
    let spellPro = new Promise(
      function(resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            console.log(JSON.stringify(res))
            resolve(res);
          }
        })
      }
    );
    let datas = false;
    datas = spellPro.then(function(rs) {
      wx.hideLoading();
      return rs.data;
    });
    return datas;
  },
  daojishi: function(flag = '') {
    console.log("-----daojishi-----")
    this.setData({
      res_img: 'fuxi_xhjc_dui_press@2x.png',
      res_dis: 'none',
      res_color: '#333333'
    })
    let that = this;
    clearInterval(this.data.timer);
    //判断是否为最后一题答完了
    if (that.data.curIndex == that.data.worldList.length) {
      clearInterval(this.data.timer);
      //提交数据
      let spellRsPro = this.upResult();
      spellRsPro.then(function(res) {
        if (res.data.code == 1) {
          app.globalData.spellUpresult = res.data.data
          wx.redirectTo({
            url: './spellReport/spellReport',
          })
        } else if (res.data.code == 10001) {
          wx.redirectTo({
            url: '/pages/login/login',
          })
        } else {
          wx.showToast({
            title: res.data.info,
            icon: 'none',
            duration: 2000
          })
        }
      });
      return false;
    }
    if (flag == 'pass') {
      that.nextPass();
    }
    that.data.timer = setInterval(function() {
      app.globalData.taskTwoMinuts = app.globalData.taskTwoMinuts + 1;
      let num = parseInt(that.data.gameSecond) - 1
      if (num >= 0) {
        if (num < 10 && num >= 0) {
          num = "0" + num.toString();
        }
        that.setData({
          gameSecond: num
        });
      } else {
        clearInterval(that.data.timer);
      }

      if (parseInt(that.data.gameSecond) <= 0) {
        clearInterval(that.data.timer);
        that.daojishi('pass');
      }
    }, 1000);
  }, 

  //播放音
  playmp3: function(mp3url) { //播放音效
    // let innerAudioContext = wx.createInnerAudioContext()
    // innerAudioContext.autoplay = false;
    // innerAudioContext.loop = false;
    // innerAudioContext.src = app.globalData.mp3.selected;
    // innerAudioContext.src = mp3url;
    // innerAudioContext.play();
    this.data.innerAudioContext.src = mp3url;
    this.data.innerAudioContext.play();

  },
  replay: function() {
    this.playmp3(this.data.curWord.vedio_url);
  },
  upResult: function() { //提交结果
    let that = this;
    that.collectWrong();
    console.log("提交的时候的错词为：", this.data.errword);
    let paramArr = {
      type: 4,
      allword: this.data.allword.join(','),
      errword: this.data.errword.join(','),
      access_token: app.globalData.studentInfo.access_token,
      date: app.globalData.studyDate
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "review/upresult?sign=" + sign;
    let spellRsPro = new Promise(
      function(resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }
    );
    return spellRsPro;
  },
  collectWrong: function() {
    for (let ele of this.data.allword) {
      if (this.data.rightWord.indexOf(ele) == -1) {
        this.data.errword.push(ele)
      }
    }
  },
  totalInit: function() {
    clearInterval(this.data.timer);
    this.setData({
      percent: 0,
      totalNum: 0,
      imageUrl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
      gameSecond: 50,
      gameSecond2: 50,
      timer: '',
      worldList: {},
      curWord: {},
      spellWord: '',
      curIndex: 0,
      maskDis: 'flex',
      jbDis: 'flex',
      curSplit: -1,
      choiceArr: [],
      spellWrongTime: 0,
      errword: [],
      allword: [],
      rightWord: [],
      res_img: 'fuxi_xhjc_dui_press@2x.png',
      res_color: "",
      res_dis: "false"
    })

  }

})